package com.example.userprovider.service;

import com.example.userprovider.domain.Member;
import com.example.userprovider.dto.AuthLoginDto;
import com.example.userprovider.utils.JwtGeneratorUtils;
import org.example.api.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录方法抽象类
 * @author
 * @date 2021-4-16 15:09
 */

public abstract class AbstractLogin implements ILogin {
    Logger logger = LoggerFactory.getLogger(AbstractLogin.class);
    public static ConcurrentHashMap<Integer,AbstractLogin> loginMap = new ConcurrentHashMap<>();
    @PostConstruct
    public void init(){
        loginMap.put(getLoginType(),this);
    }

    /**
     * 获取登录类型
     * @return
     */
    public abstract Integer getLoginType();

    @Override
    public R doLogin(AuthLoginDto dto) {
        logger.info("begin AbstractLogin.doLogin："+dto);
        // 验证参数
        validate(dto);
        Member member = doProcessor(dto);
        Map<String,Object> payload = new HashMap<>();
        payload.put("uid",member.getId());
        payload.put("name",member.getUsername());
        String token = JwtGeneratorUtils.generateToken(payload);
        return new R.Builder<String>().setData(token).buildOk();
    }

    /**
     * 校验用户
     * @param dto
     */
    public abstract void validate(AuthLoginDto dto);

    /**
     * 校验用户
     * @param dto
     * @return
     */
    public abstract Member doProcessor(AuthLoginDto dto);

}
